function updateAnimatedMeshPlaySpeed()
{
  var screen = this.game.getScreen(MESH_MANAGER_SCREEN_ID);
  var node = screen.aniNode;
  node.animationSpeed = parseFloat( getTextFromInput("SkinnedMeshTab_PlaySpeed") );
}
function playAnimatedMesh()
{
  var screen = this.game.getScreen(MESH_MANAGER_SCREEN_ID);
  var node = screen.aniNode;
  var isLoop = document.getElementById("SkinnedMeshTab_IsLoop").checked;
  if(node.animationState==GEW_PAUSE)
  {
    node.play(isLoop); 
  }
  else if(node.animationState==GEW_STOP)
  {
    node.play(isLoop); 
  }
  else
  {
    node.pause();
  }
}
function toStartAnimatedMesh()
{
  var screen = this.game.getScreen(MESH_MANAGER_SCREEN_ID);
  var node = screen.aniNode;
  node.stop();
}
function toEndAnimatedMesh()
{
  var screen = this.game.getScreen(MESH_MANAGER_SCREEN_ID);
  var node = screen.aniNode;
  node.pause();
  var dur = node.mesh.durations[ node.animationIdx ];
  node.ellapseTime = dur;
}
function updateAnimationInfo()
{
  var screen = this.game.getScreen(MESH_MANAGER_SCREEN_ID);
  var node = screen.aniNode;
  var idx = document.getElementById("SkinnedMeshTab_AnimationList").selectedIndex;
  node.setAnimation(idx);
  document.getElementById("SkinnedMeshTab_KeyCount").value = node.mesh.animationKeys[idx];
  document.getElementById("SkinnedMeshTab_Duration").value = node.mesh.durations[idx];
}
function updateMeshScreenDisplayOption()
{
  var screen = this.game.getScreen(MESH_MANAGER_SCREEN_ID);
  screen.isDisplayAabb = document.getElementById("MeshManager_DisplayAabb").checked;
  screen.isDisplaySphere = document.getElementById("MeshManager_DisplaySphere").checked;
  var texName = getTextFromList("MeshManager_DisplayTextureList");
  var texture;
  if(texName=="")
    texture = screen.texture;
  else
    texture = this.game.resourceManager.getTexture(texName);
  screen.phongMaterial.texture = texture;
  screen.phongSkinnedMaterial.texture = texture;
}
function changeMeshDisplayLOD()
{
  var dropList = document.getElementById("StaticMeshTab_Level");
  var level = dropList.selectedIndex;
  var screen = this.game.getScreen(MESH_MANAGER_SCREEN_ID);
  screen.node.currentLOD = level;
  document.getElementById("StaticMeshTab_IndicesCount").value = screen.activeMesh.indices[screen.node.currentLOD].length;
}
function displayMesh()
{
  var list = document.getElementById("MeshManager_MeshList");
  var selectId = list.selectedIndex;
  var op = list.options[selectId];
  if(!op)
    return;
  var meshName = op.text;
  var screen = this.game.getScreen(MESH_MANAGER_SCREEN_ID);
  var mesh = this.game.resourceManager.getMesh(meshName);
  screen.setActiveMesh(meshName);
  var type = mesh.meshType;
  switch(type)
  {
    case GEW_STATIC_MESH:
      clearInfoTab();
      addInfoTab("infoTabs/StaticMeshTab.html","Static Mesh");
      document.getElementById("StaticMeshTab_URL").value = mesh.url;
      document.getElementById("StaticMeshTab_RenderType").value = mesh.renderType;
      document.getElementById("StaticMeshTab_VerticesCount").value = mesh.vertices.length/3;
      document.getElementById("StaticMeshTab_LODCount").value = mesh.lodNumber;
      document.getElementById("StaticMeshTab_IsCreatedVBO").value = mesh.isCreateVBO;
      
      if (mesh.indices) {
        var dropList = document.getElementById("StaticMeshTab_Level");
        // Remove all old entries
        dropList.options.length = 0
        // Update new entries
        for (var i = 0; i < mesh.lodNumber; i++) {
          var op = document.createElement('option');
          op.text = i.toString();
          dropList.add(op, null);
        }
        dropList.selectedIndex = screen.node.currentLOD;
        document.getElementById("StaticMeshTab_IndicesCount").value = mesh.indices[screen.node.currentLOD].length;
      }
      break;
    case GEW_SKINNED_MESH:
      clearInfoTab();
      addInfoTab("infoTabs/SkinnedMeshTab.html","Skinned Mesh");
      document.getElementById("SkinnedMeshTab_URL").value = mesh.url;
      document.getElementById("SkinnedMeshTab_VerticesCount").value = mesh.vertices.length/3;
      document.getElementById("SkinnedMeshTab_IndicesCount").value = mesh.indices[0].length;
      document.getElementById("SkinnedMeshTab_LODCount").value = mesh.lodNumber;
      document.getElementById("SkinnedMeshTab_IsCreatedVBO").value = mesh.isCreateVBO;
      document.getElementById("SkinnedMeshTab_FPS").value = mesh.fps;
      
      var dropList = document.getElementById("SkinnedMeshTab_AnimationList");
      // Remove all old entries
      dropList.options.length = 0
      // Update new entries
      var animationList = mesh.animationKeys;
      for (var i = 0; i < animationList.length; i++) {
        var op = document.createElement('option');
        op.text = i;
        dropList.add(op, null);
      }
      updateAnimationInfo();
      break;
  }  
}
function addMesh()
{
  var name  = document.getElementById("addMeshDialog_Name").value;
  var url = document.getElementById("addMeshDialog_URL").value;
  var isCreateVBO = document.getElementById("addMeshDialog_IsCreateVBO").checked;
  
  this.game.resourceManager.load(name,url,true,false,isCreateVBO);
  updateMeshList(name);
  $("#addMeshDialog").dialog("close");
  setTimeout(function(){displayMesh()},500);
}
function removeMesh()
{
  var list = document.getElementById("MeshManager_MeshList");
  var selectId = list.selectedIndex;
  var op = list.options[selectId];
  var meshName = op.text;
  if (confirm("Are you sure want to delete '" + meshName + "' mesh?")) 
  {
    this.game.resourceManager.removeMesh(meshName);
    updateMeshList();
  }
}


// List of all ui_mesh_select_element need to be update
var UI_Mesh_Element_Ids = [
  "MeshManager_MeshList",
];
function updateMeshList(name)
{
  var meshList = this.game.resourceManager.meshManager.meshList;
  var temp = [];
  for (var mesh in meshList) {
    temp.push(mesh);
  }
  temp.sort();
  
  var elementNum = UI_Mesh_Element_Ids.length;
  for (var ele = 0; ele < elementNum; ele++) {
    var dropList = document.getElementById(UI_Mesh_Element_Ids[ele]);
    // Remove all old entries
    dropList.options.length = 0
    // Update new entries
    for (var i = 0; i < temp.length; i++) {
      var op = document.createElement('option');
      op.text = temp[i];
      dropList.add(op, null);
      if (name && name == temp[i])
        dropList.selectedIndex = i;
    }
  }
}
function updateMeshListInto(list_id,name)
{
  var meshList = this.game.resourceManager.meshManager.meshList;
  var temp = [""];
  for (var mesh in meshList) {
    temp.push(mesh);
  }
  temp.sort();
  var dropList = document.getElementById(list_id);
  // Remove all old entries
  dropList.options.length = 0
  // Update new entries
  for (var i = 0; i < temp.length; i++) {
    var op = document.createElement('option');
    op.text = temp[i];
    dropList.add(op, null);
    if (name && name == temp[i])
      dropList.selectedIndex = i;
  }  
}
function MeshManagerScreen(game)
{
  gewScreen.call(this, game);
  this.scene3d = new gewScene3D(this.game);
  this.activeMesh = null;
  this.isDisplayAabb = false;
  this.isDisplaySphere = false;
  
  this.texture = new gewTexture(game.gl,gl.TEXTURE_2D);
  gl.bindTexture(gl.TEXTURE_2D, this.texture.glName);
  var byteNum = 4 * 8 * 8;
  var grayData = new WebGLUnsignedByteArray(byteNum);
  for(var i=0;i<byteNum;i++)
    grayData[i] = 120;
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 8, 8, 0, gl.RGBA, gl.UNSIGNED_BYTE, grayData);
  this.texture.isReady = true;
  this.setActiveMesh = function(name)
  {
    this.activeMesh = this.game.resourceManager.getMesh(name);
    if (this.activeMesh) {
      if (this.activeMesh.meshType == GEW_STATIC_MESH) {
        this.node.setMesh(this.activeMesh);
        this.aniNode.mesh = null;
      }
      else if (this.activeMesh.meshType == GEW_SKINNED_MESH) {
        this.aniNode.setMesh(this.activeMesh);
        this.aniNode.play(false);
        this.aniNode.setAnimation(0);
        this.node.mesh = null;
      }
    }
    this.resetCamera();
  }
  this.onTick = function(mls)
  {
    var gl = this.game.gl;
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    if (this.activeMesh) {
      this.scene3d.render();
      // Draw gridv
      var drawer = this.scene3d.debugDrawer;
      gl.enable(gl.DEPTH_TEST);
      gl.enableVertexAttribArray(drawer.inPosition);
      gl.uniform4f(drawer.inColor,0.5,0.5,0.5,1.);
      drawGrid(gl,drawer,50);
      if (this.isDisplayAabb) {
        if (this.activeMesh.meshType == GEW_STATIC_MESH) {
          drawAabb(gl, drawer, this.node.worldAabb, new gewVec3(1.0, 0.0, 0.0));
        }
        else 
          if (this.activeMesh.meshType == GEW_SKINNED_MESH) {
            drawAabb(gl, drawer, this.aniNode.worldAabb, new gewVec3(1.0, 0.0, 0.0));
          }
      }
      if (this.isDisplaySphere) {
        gl.uniform4f(drawer.inColor,0.0,1.0,0.0,1.);
        if (this.activeMesh.meshType == GEW_STATIC_MESH) {
          drawWireSphere(gl, drawer, this.node.worldSphere.center, this.node.worldSphere.radius, 15, 15);
        }
        else 
          if (this.activeMesh.meshType == GEW_SKINNED_MESH) {
            drawWireSphere(gl, drawer, this.aniNode.worldSphere.center, this.aniNode.worldSphere.radius, 15, 15);
          }
      }      
      gl.disableVertexAttribArray(drawer.inPosition);
    }
    elapseMls += mls;
    frameCount++;
    if (elapseMls >= 2000) 
    {
      var fps = frameCount / 2;
      renderFPS.value =  fps;
      elapseMls = 0;
      frameCount = 0;
    }
  }
  this.resetCamera = function()
  {
    var cam = this.camera;
    var game = this.game;
    //cam.setPitch(-GEW_MATH_PI / 4);
    if (this.activeMesh&&this.activeMesh.boundingSphere) {
      var height = this.activeMesh.boundingSphere.radius * 3;
      if(height>500)
        height = 500.0;
    }
    else 
      var height = 100;
    cam.setDesiredPos(new gewVec3(0.0, height, height));
    //cam.    
  }
  this.init = function()
  {
    var game = this.game;
    var gl = this.game.gl;
    var scene3d = this.scene3d;
    var root = scene3d.root;
    var camera_system = scene3d.camera_system;
    // init camera
    var cam = camera_system.createCamera(gewWorldCamera, root);  
    this.camera = cam;
    cam.setFov(60.0);
    cam.setAspectRatio(game.width / game.height);
    cam.setNear(0.1);
    cam.setFar(1000);
    cam.setViewport(0, 0, game.width, game.height);
    this.resetCamera();
    camera_system.setActiveCamera(cam);    
    var effect = new gewPhongEffect(game);
    var phongSkinnedE = new gewPhongSkinnedEffect(game);   
    scene3d.addEffect(effect);
    scene3d.addEffect(phongSkinnedE);    
    var material = new gewPhongMaterial(effect);
    material.faceCulling = false;
    var skinnedM = new gewPhongMaterial(phongSkinnedE);    
    var rmanager = game.resourceManager;    
    material.texture = this.texture;
    skinnedM.texture = this.texture;
    
    this.phongMaterial = material;
    this.phongSkinnedMaterial = skinnedM;
    this.node = new gewMeshNode();
    this.node.addMaterial(material);
    this.aniNode = new gewAnimatedMeshNode();
    this.aniNode.addMaterial(skinnedM);
    root.appendChild(this.node);
    root.appendChild(this.aniNode);
  }
  this.isDrag = false;
  this.onMouseDown = function(e)
  {
    this.camera.onMouseDown(e);
  }
  this.onMouseMove = function(e)
  {
    var distance = this.camera.m_desired_pos.getLength();
    distance = distance.toFixed(2);
    document.getElementById("MeshManager_DistanceFromCamera").value = distance;
    this.camera.onMouseMove(e);    
  }
  this.onMouseOut = function(e)
  {
    document.body.style.cursor='default' 
  }
  this.onMouseUp = function(e)
  {
    var distance = this.camera.m_desired_pos.getLength();
    distance = distance.toFixed(2);
    document.getElementById("MeshManager_DistanceFromCamera").value = distance;
    this.camera.onMouseUp(e);
  }
  this.onMouseWheel = function(e)
  {
    var distance = this.camera.m_desired_pos.getLength();
    distance = distance.toFixed(2);
    document.getElementById("MeshManager_DistanceFromCamera").value = distance;
    this.camera.onMouseWheel(e);
  }
  this.onKeyDown = function(e)
  {    
    var distance = this.camera.m_desired_pos.getLength();
    distance = distance.toFixed(2);
    document.getElementById("MeshManager_DistanceFromCamera").value = distance;
    this.camera.onKeyDown(e);
  }
  this.onKeyPress = function(e)
  {
    var distance = this.camera.m_desired_pos.getLength();
    distance = distance.toFixed(2);
    document.getElementById("MeshManager_DistanceFromCamera").value = distance;
    this.camera.onKeyPress(e);
  }
  this.onKeyUp = function(e)
  {
    var distance = this.camera.m_desired_pos.getLength();
    distance = distance.toFixed(2);
    document.getElementById("MeshManager_DistanceFromCamera").value = distance;
    this.camera.onKeyUp(e);
  }
}